import React from 'react';
import { Tree, message } from 'antd';
import { findIndex } from 'lodash';
import { FilePdfOutlined } from '@ant-design/icons';
import { connect, Dispatch } from 'umi';
import moment from 'moment';
import { StateType } from './model';

interface IssueListProps {
  project: any;
  dispatch: Dispatch;
  data: any[];
  selectedBp: any;
  onSave: (
    pid?: string,
    mid?: string,
    uid?: string,
    bid?: string,
    opinion?: string,
    drawingMarks?: any,
  ) => void;
  onIssueSelect: (issue: any) => void;
  onHistoryBpSelected: (bp: any) => void;
  onCollapsed: (val: any) => void;
}

const IssueList: React.FC<IssueListProps> = (props) => {
  const {
    project: { bpHistory, issueListState },
    dispatch,
    data,
    selectedBp,
  } = props;
  const { expandedKeys, checkedKeys, selectedKeys, autoExpandParent } = issueListState;

  const onExpand = (eKeys: any) => {
    dispatch({
      type: 'project/save',
      payload: {
        issueListState: {
          ...issueListState,
          expandedKeys: eKeys,
          autoExpandParent: false,
        },
      },
    });
  };

  const onCheck = (cKeys: any) => {
    let bph = null;
    let compareList = [];

    let drawingUrl = '';
    if (cKeys.length > 2) {
      cKeys.shift();
      const [t] = data.filter((d) => d.id === cKeys[1]);
      bph = t;
      drawingUrl = '';
    } else if (cKeys.length === 2) {
      const [t] = data.filter((d) => d.id === cKeys[1]);
      bph = t;
      drawingUrl = t.url;
    } else if (cKeys.length === 1) {
      const [t] = data.filter((d) => d.id === cKeys[0]);
      bph = t;
      drawingUrl = t.url;
    } else {
      drawingUrl = '';
    }
    if (cKeys.length === 2) {
      compareList = bpHistory.filter((h: any) => findIndex(cKeys, (k) => k === h.id) >= 0);
    }
    dispatch({
      type: 'project/save',
      payload: {
        compareList,
        drawingUrl,
        drawingMarks: [],
        issueListState: {
          ...issueListState,
          expandedKeys: cKeys,
          checkedKeys: cKeys,
          selectedKeys: [],
          selectedBph: bph,
        },
        pdfMarkable: true,
      },
    });
    // onHistoryBpSelected(bph);
  };

  /**
   * 问题选中处理
   */
  const handleIssueSelect = (sKeys: any, info: any) => {
    const {
      node: {
        bhid, // 图纸历史记录ID
        marks, // 问题标注
        opinion, // 意见描述
      },
    } = info;
    console.log(sKeys);
    const temp = data.filter((d) => d.id === bhid);
    const tSKey1 = sKeys[0];
    const tSkey2 = selectedKeys.length > 0 ? selectedKeys[0] : null;
    const reselect = tSKey1 === tSkey2; // 重复选择
    if (temp.length === 0) {
      message.warning('数据已不存在，请刷新页面！');
      dispatch({
        type: 'project/save',
        payload: {
          issueListState: {
            ...issueListState,
            selectedKeys: [],
            selectedBph: [],
          },
          pdfMarkable: false,
          editIssueCollapsed: true,
          editIssueFormValues: {
            bhid: '',
          },
        },
      });
    } else {
      dispatch({
        type: 'project/save',
        payload: {
          issueListState: {
            ...issueListState,
            checkedKeys: [bhid],
            selectedKeys: reselect ? [] : sKeys,
            selectedBph: temp[0],
          },
          pdfMarkable: reselect,
          drawingUrl: temp[0].url,
          drawingMarks: reselect ? [] : marks.map((m: any) => JSON.parse(m.data)),
          editIssueCollapsed: reselect,
          editIssueReadonly: reselect,
          editIssueFormValues: {
            bhid,
            opinion,
          },
        },
      });
    }
  };

  const bpIssueTree = data.map((bp) => ({
    title: `${selectedBp && selectedBp.title}-${
      bp.version === 0 ? '初审' : `第${bp.version}次复审`
    }`,
    key: bp.id,
    icon: <FilePdfOutlined />,
    children: !bp.issues
      ? []
      : bp.issues.map((item: any, i: number) => ({
          title: (
            <div
              style={{
                backgroundColor:
                  selectedKeys && selectedKeys.length > 0 && selectedKeys[0] === item.id
                    ? '#bae7ff'
                    : 'white',
              }}
            >
              <span style={{ padding: '0 5px' }}>{`意见-${i + 1}（${moment(item.createTime).format(
                'YYYY-MM-DD HH:mm:ss',
              )}）`}</span>
            </div>
          ),
          key: item.id,
          checkable: false,
          selectable: true,
          ...item,
        })),
    ...bp,
  }));

  return (
    <>
      <Tree
        checkable
        showIcon
        showLine
        selectable={false}
        onExpand={onExpand}
        expandedKeys={expandedKeys}
        autoExpandParent={autoExpandParent}
        onCheck={onCheck}
        checkedKeys={checkedKeys}
        onSelect={handleIssueSelect}
        selectedKeys={selectedKeys}
        treeData={bpIssueTree}
      />
    </>
  );
};

export default connect(
  ({
    project,
  }: {
    project: StateType;
    loading: {
      effects: { [key: string]: boolean };
    };
  }) => ({
    project,
  }),
)(IssueList);
